package com.magic.gre.ui.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.magic.gre.R;
import com.magic.gre.adapter.BannerAdapter;
import com.magic.gre.adapter.HomeAdapter;
import com.magic.gre.adapter.ThesaurusAdapter2;
import com.magic.gre.base.fragment.BaseMVPFragment;
import com.magic.gre.behavior.MainHeaderBehavior;
import com.magic.gre.callback.OnBannerItemClickListener;
import com.magic.gre.entity.BannerBean;
import com.magic.gre.entity.OptionBean;
import com.magic.gre.entity.ThesaurusBean;
import com.magic.gre.helper.Apphelper;
import com.magic.gre.helper.BannerScaleHelper;
import com.magic.gre.mvp.contract.HomeContract;
import com.magic.gre.mvp.presenter.HomePresenterImpl;
import com.magic.gre.ui.activity.ChooseUnitActivity;
import com.magic.gre.ui.activity.NewWordsActivity;
import com.magic.gre.ui.activity.RipeWordsActivity;
import com.magic.gre.ui.activity.SearchActivity;
import com.magic.gre.ui.activity.WebActivity;
import com.magic.gre.ui.activity.WordCountActvity;
import com.magic.gre.utils.PermissonUtils;
import com.magic.gre.widget.BannerRecyclerView;
import com.noname.lib_base_java.entity.MsgEvent;
import com.noname.lib_base_java.util.PathUtil;
import com.noname.lib_base_java.util.StatusBarUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tmall.ultraviewpager.UltraViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Author: Lmoumou
 * Date: 2019-01-07 15:25
 * 文件名: HomeFragment
 * 描述:
 */
public class HomeFragment extends BaseMVPFragment<HomePresenterImpl> implements HomeContract.View,
        HomeAdapter.OnHomeAdapterListener,ThesaurusAdapter2.OnThesaurusAdapter2Listener {

    @BindView(R.id.mUltraViewPager)
    UltraViewPager mUltraViewPager;
    @BindView(R.id.status_bar_v)
    View statusView;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.title_ll)
    LinearLayout titleLl;
    @BindView(R.id.header)
    FrameLayout header;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    private BannerRecyclerView bannerRcy;
    private List<BannerBean> bannerList = new ArrayList<>();
    private List<ThesaurusBean> thesaurusBeanList = new ArrayList<>();
    private HomeAdapter adapter;
    private LinearLayoutManager layoutManager;
    private MainHeaderBehavior mainHeaderBehavior;
    private RxPermissions rxPermissions;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected HomePresenterImpl creatPresenter() {
        return new HomePresenterImpl(this);
    }

    @Override
    protected void lazyLoad() {
        mPresenter.pBannerData();
        mPresenter.pOption();
        mPresenter.pThesaurusList();
    }

    @Override
    protected void netOverride() {

    }

    @Override
    protected void handlerMsg(MsgEvent msgEvent) {
        super.handlerMsg(msgEvent);
        switch (msgEvent.getEvent()) {
            case MsgEvent.LEARN_HISTORY:
                mPresenter.pThesaurusList();
                break;
        }
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        super.initView(view, savedInstanceState);
        StatusBarUtil.setHeight(mContext, statusView);
        registerRxBus();
        adapter = new HomeAdapter(mContext, new ArrayList<String>());
        adapter.setOnHomeAdapterListener(this);
        mRecyclerView.setLayoutManager(layoutManager = new LinearLayoutManager(mContext));
        mRecyclerView.setAdapter(adapter);
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) header.getLayoutParams();
        mainHeaderBehavior = (MainHeaderBehavior) params.getBehavior();


    }

    @OnClick(value = {R.id.iv_down, R.id.iv_search})
    protected void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_down:
                layoutManager.scrollToPositionWithOffset(0, 0);
                mainHeaderBehavior.openHeader();
                break;
            case R.id.iv_search:
                SearchActivity.startThis(mContext);
                break;
        }
    }

    /**
     * 初始化Banner
     */
    private void initBanner() {

        BannerAdapter<BannerBean> bannerAdapter = new BannerAdapter<>(mContext);
        bannerAdapter.setData(bannerList);

        bannerAdapter.setOnBannerItemClickListener(new OnBannerItemClickListener<BannerBean>() {
            @Override
            public void onBannerItemClick(BannerBean bannerBean, int position) {
                WebActivity.startThis(mContext, bannerBean.getName(), PathUtil.urlPath(bannerBean.getLink()));
            }
        });

        mUltraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
        mUltraViewPager.setAdapter(bannerAdapter);

        mUltraViewPager.initIndicator();

        mUltraViewPager.getIndicator()
                .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                .setFocusColor(Color.parseColor("#93ADC1"))
                .setNormalColor(Color.WHITE)
                .setFocusResId(R.drawable.indicator_banner_home)
                .setNormalResId(R.drawable.indicator_banner_home_noemal)
                .setMargin(0, 0, 0, 10)
                .setRadius((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3.0f, mContext.getResources().getDisplayMetrics()));
        mUltraViewPager.getIndicator().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        mUltraViewPager.getIndicator().build();
        mUltraViewPager.setInfiniteLoop(true);
        mUltraViewPager.setAutoScroll(2000);
    }

    private BannerScaleHelper mBannerScaleHelper = null;

    private void initBanner2() {
        ThesaurusAdapter2 bannerAdapter = new ThesaurusAdapter2(mContext, thesaurusBeanList);
        bannerAdapter.setOnThesaurusAdapter2Listener(this);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        bannerRcy.setNestedScrollingEnabled(false);
        bannerRcy.setLayoutManager(linearLayoutManager);
        bannerRcy.setAdapter(bannerAdapter);
        mBannerScaleHelper = new BannerScaleHelper();
        mBannerScaleHelper.setFirstItemPos(Apphelper.getThesaurusPosition());
        mBannerScaleHelper.attachToRecyclerView(bannerRcy);
//        mBannerScaleHelper.scrollToPosition(1002);
//        linearLayoutManager.scrollToPositionWithOffset(1002,0);
    }

    @Override
    public void onInitViewPaher(BannerRecyclerView bannerRcy) {
        this.bannerRcy = bannerRcy;
    }

    @Override
    public void onItemClick(View view) {
        if (isValidAccount()){
            switch (view.getId()) {
                case R.id.new_words_tv:
                    NewWordsActivity.startThis(mContext);
                    break;
                case R.id.ripe_words_tv:
                    RipeWordsActivity.startThis(mContext);
                    break;
                case R.id.count_tv:
                    WordCountActvity.startThis(mContext);
                    break;
            }
        }

    }

    @Override
    public void onDialogMiss() {

    }

    @Override
    public void vBannerData(List<BannerBean> beanList) {
        bannerList.clear();
        bannerList.addAll(beanList);
        initBanner();
    }

    @Override
    public void vOption(OptionBean optionBean) {
        adapter.setOption(optionBean);
    }

    @Override
    public void vThesaurusList(List<ThesaurusBean> thesaurusBeanList) {
        this.thesaurusBeanList.clear();
        this.thesaurusBeanList.addAll(thesaurusBeanList);
        initBanner2();
    }

    @SuppressLint("CheckResult")
    @Override
    public void onThesaurusItemClick(final String id, final int position) {
        if (rxPermissions==null){
            rxPermissions=new RxPermissions(this);
        }
        rxPermissions.request(PermissonUtils.READ_WRITE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean){
                            Apphelper.putThesaurusPosition(position);
                            ChooseUnitActivity.startThis(mContext,id);
                        }
                    }
                });

    }
}
